package com.fanshuai.soring.boot.webflux.metrics;

import io.netty.buffer.ByteBufAllocator;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.HandlerAdapter;
import org.springframework.web.reactive.HandlerResult;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;

public class ReactiveMetricsHandlerAdapter implements HandlerAdapter {
    DataBufferFactory factory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);

    @Override
    public boolean supports(Object o) {
        return o instanceof ReactiveMetricsOutput;
    }

    @Override
    public Mono<HandlerResult> handle(ServerWebExchange serverWebExchange, Object o) {
        ReactiveMetricsOutput output = (ReactiveMetricsOutput) o;
        Mono<DataBuffer> bufferMono = output.metrics().map(s -> {
            return factory.wrap(s.getBytes(StandardCharsets.UTF_8));
        });

        ServerHttpResponse response = serverWebExchange.getResponse();
        Mono<Void> result = response.writeAndFlushWith(Mono.just(bufferMono));
        return result.then(Mono.empty());
    }
}
